package com.zuthub.web.controller.tool;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@Component
public class OssUtils {

    /**
     * log日志
     */
    public static final Logger logger = LoggerFactory.getLogger(OssUtils.class);

    @Value("${aliyun.endpoint}")
    private String endpoint;
    @Value("${aliyun.access-id}")
    private String accessKeyId;
    @Value("${aliyun.access-key}")
    private String accessKeySecret;
    @Value("${aliyun.bucket}")
    private String bucketName;




    //上传视频
    public String uploadVideo(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        try {
            InputStream stream=file.getInputStream();
            OSSClient client=new OSSClient(endpoint,accessKeyId,accessKeySecret);
            PutObjectResult result=client.putObject(bucketName,originalFilename,stream);
            client.shutdown();
            return "https://guitarweb.oss-cn-beijing.aliyuncs.com/"+originalFilename;
        } catch (Exception e) {
            throw new RuntimeException("视频上传失败");
        }
    }




    /**
     * Description: 判断OSS服务文件上传时文件的contentType
     */
    public static String getcontentType(String filenameExtension) {
        if (filenameExtension.equalsIgnoreCase("bmp")) {
            return "image/bmp";
        }
        if (filenameExtension.equalsIgnoreCase("gif")) {
            return "image/gif";
        }
        if (filenameExtension.equalsIgnoreCase("jpeg") || filenameExtension.equalsIgnoreCase("jpg")
                || filenameExtension.equalsIgnoreCase("png")) {
            return "image/jpeg";
        }
        if (filenameExtension.equalsIgnoreCase("html")) {
            return "text/html";
        }
        if (filenameExtension.equalsIgnoreCase("txt")) {
            return "text/plain";
        }
        if (filenameExtension.equalsIgnoreCase("vsd")) {
            return "application/vnd.visio";
        }
        if (filenameExtension.equalsIgnoreCase("pptx") || filenameExtension.equalsIgnoreCase("ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (filenameExtension.equalsIgnoreCase("docx") || filenameExtension.equalsIgnoreCase("doc")) {
            return "application/msword";
        }
        if (filenameExtension.equalsIgnoreCase("xml")) {
            return "text/xml";
        }
        return "image/jpeg";
    }

}
